import { logoutApi } from '~@/api/common/login'
import { getRouteMenusApi } from '~@/api/common/menu'
import { getUserInfoApi } from '~@/api/common/user'
import { rootRoute } from '~@/router/constant'
import { generateFlatRoutes, generateRoutes, generateTreeRoutes } from '~@/router/generate-route'
import { DYNAMIC_LOAD_WAY, DynamicLoadEnum } from '~@/utils/constant'

export const useUserStore = defineStore('user', () => {
  const routerData = shallowRef()
  const menuData = shallowRef([])
  const userInfo = shallowRef()
  const permissions = shallowRef([]) // 存储权限列表
  const token = useAuthorization()
  const avatar = computed(() => userInfo.value?.avatar)
  const username = computed(() => userInfo.value?.userName)
  const roles = computed(() => userInfo.value?.roles)
  const userId = computed(() => userInfo.value?.userId)
  const getMenuRoutes = async () => {
    const { data } = await getRouteMenusApi()
    return generateTreeRoutes(data ?? [])
  }
  const generateDynamicRoutes = async () => {
    const dynamicLoadWay = DYNAMIC_LOAD_WAY === DynamicLoadEnum.BACKEND ? getMenuRoutes : generateRoutes
    const { menuData: treeMenuData, routeData } = await dynamicLoadWay()
    menuData.value = treeMenuData
    routerData.value = {
      ...rootRoute,
      children: generateFlatRoutes(routeData),
    }
    return routerData.value
  }
  const getUserInfo = async () => {
    const { data } = await getUserInfoApi()
    userInfo.value = data
    permissions.value = data.permissions
    localStorage.setItem('permissions', JSON.stringify(permissions.value)) // 保存权限
  }
  // 判断是否有某个权限
  const hasPermission = (permission) => {
    return permissions.value && permissions.value.includes(permission)
  }
  const logout = async () => {
    try {
      await logoutApi()
    }
    finally {
      token.value = null
      userInfo.value = void 0
      routerData.value = void 0
      menuData.value = []
      permissions.value = []
      localStorage.removeItem('permissions')
    }
  }
  return {
    userInfo,
    permissions,
    roles,
    getUserInfo,
    hasPermission,
    logout,
    routerData,
    menuData,
    generateDynamicRoutes,
    avatar,
    username,
    userId,
  }
})
